package com.gitee.wsl.compose.ext.text

import androidx.compose.material3.LocalTextStyle
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalFontFamilyResolver
import androidx.compose.ui.text.Paragraph
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.sp


@Composable
fun TextStyle.findTextSize(
    text: String,
    maxLines: Int = Int.MAX_VALUE,
    ellipsis: Boolean = false,
    constraints: Constraints,
    minTextSize: Float,
    maxTextSize: Float
): Float {
    if (maxTextSize - minTextSize < 1) {
        return minTextSize
    }
    val style = this

    val textOverflow = if (ellipsis) TextOverflow.Ellipsis else TextOverflow.Clip

    val sizeCheck = if (maxTextSize.isInfinite()) {
        // Protect against a tiny minTextSize
        if (minTextSize < 1f) {
            minTextSize
        } else {
            minTextSize * 2f
        }
    } else {
        (maxTextSize + minTextSize) / 2.0f
    }

    val fontResolver = LocalFontFamilyResolver.current
    val density = LocalDensity.current

    val paragraph = Paragraph(
        text = text,
        style = style.copy(fontSize = sizeCheck.sp),
        maxLines = maxLines,
        constraints = constraints.copy(minWidth = 0, minHeight = 0),
        density = density,
        fontFamilyResolver = fontResolver,
        overflow = textOverflow
    )

    return if (paragraph.didExceedMaxLines ||
        paragraph.height > constraints.maxHeight ||
        paragraph.width > constraints.maxWidth
    ) {
        findTextSize(text,  maxLines, ellipsis, constraints, minTextSize, sizeCheck)
    } else {
        findTextSize(text,  maxLines, ellipsis, constraints, sizeCheck, maxTextSize)
    }
}